<?php


namespace app\admin\product\model;

use app\command\model\game\Shop;
use Exception;
use mb\helper\Collection;
use think\Db;

class Product
{
    protected static $table = 'products';

    public static function getTyps()
    {
        /**
         * sunice
         */
        return [
            'k3' => '快3',
              'c3'    => '印度三色彩',
            'pk10' => 'pk10',
//            'amq' => '澳门区',
//            'xgq' => '香港区',
//            'twq' => '台湾区',
            'x5' => '11选5',
            'kl8' => '快乐8',
            'pc28' => 'pc28',
            'ssc' => '时时彩',
            'lhc' => '六合彩',
            'kl10f' => '快乐10分',
        ];
    }
    /**
     * @param array $row
     * @return bool|int|string
     */
    public static function add(array $row)
    {
        $newRow = Collection::elements([
            'categoryId',
            'type',
            'expectCount',
            'name',
            'sort',
            'kills',
            'sys',
            'timeInterval',
            'timeExpect',
            'lang',
            'hot'
        ], $row);
        $newRow['lang'] = serialize($newRow['lang']);
        $newRow['timeCreated'] = time();
        $newRow['status'] = 'normal';
        $newRow = Collection::keyStyle($newRow, Collection::NAME_STYLE_C);
        try {
            return Db::table(self::$table)
                ->insertGetId($newRow);
        } catch (Exception $e) {
          
            return error($e->getCode(), $e->getMessage());
        }
    }

    /**
     * @param $filter
     * @return array|Error
     */
    public static function fetch($filter,$connect = null)
    {
        $where = self::parseFilters($filter);
        try {
            if (empty($connect)) {
                $connect = Db::connect();
            }
            $row = $connect->table(self::$table)
                ->where($where)
                ->find();
            if (!empty($row)) {
                $row['time_created'] *= 1000;
                $row['lang'] = unserialize($row['lang']);
                return Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    /**
     * @param $filter
     * @return bool|Error
     */
    public static function remove($filter)
    {
        $where = self::parseFilters($filter);
        try {
            $offect = Db::table(self::$table)
                ->where($where)
                ->delete();
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @param $newState
     * @return bool|Error
     */
    public static function update($filter, $newState)
    {
        $where = self::parseFilters($filter);
        try {
            $offect = Db::table(self::$table)
                ->where($where)
                ->update($newState);
                
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @return array
     */
    public static function parseFilters($filter)
    {
        $where = [];
        if (is_array($filter)) {
            if (!empty($filter['id'])) {
                $where[] = ['id', '=', $filter['id']];
            }
            if (!empty($filter['name'])) {
                $where[] = ['name', '=', $filter['name']];
            }
            if (empty($where)) {
                throw error(-10, '参数错误必须指定id');
            }
        } else {
            $where[] = ['id', '=', intval($filter)];
        }
        return $where;
    }



    /**
     * @param array $filters
     * @param int $pIndex
     * @param int $pSize
     * @param int $total
     * @return array|Error
     */
    public static function search(array $filters, int $pIndex = 0, int $pSize = 10, int &$total = 0)
    {
        $where = [];
        if (!empty($filters['status'])) {
            $where[] = ['status', '=', $filters['status']];
        }

        if (isset($filters['sys'])) {
            $where[] = ['sys', '=', $filters['sys']];
        }

        if (!empty($filters['type'])) {
            $where[] = ['type', '=', $filters['type']];
        }
        if (!empty($filters['idMax'])) {
            $where[] = ['id', '>=', $filters['idMax']];
        }
        try {
            if (!empty($pIndex)) {
                $total = Db::table(self::$table)
                    ->where($where)
                    ->count();
            }
            $query = Db::table(self::$table)
                ->where($where);
            if (!empty($pIndex)) {
                $query->page($pIndex, $pSize);
            }
            if (!empty($filters['order'])) {
                $query->order($filters['order']);
            }
            $dataSet = $query->select();
            if (!$dataSet->isEmpty()) {
                return $dataSet->map(
                    function ($row) {
                        $row['time_created'] *= 1000;
                         if (!empty($row['lang'])) {
                            $row['lang'] = unserialize($row['lang']);
                            $row['lang'] = array_map(function ($one){
                                foreach ($one['img'] as $i=>$v){
                                     $one['img'][$i]['img'] = 'https://api.veso567.com'.$v['img'] ;
                                    $one['img'][$i]['thumbUrl'] = 'https://api.veso567.com'.$v['thumbUrl'] ; 
                                    // $one[$i]['img'] = 'https://api.veso567.com'.$v['img'] ;
                                }
                                return $one;
                            }, $row['lang']);
                        }

                        $row = Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
                        return $row;
                    }
                )->toArray();
            }
        } catch (Exception $e) {
            var_dump($e);die;
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    /**
     * 全天开奖
     * @param $time
     * @return array|\Error
     */
    public static function getDayTime($productInfo)
{
    $startTime = empty($productInfo['startTime'])?strtotime('00:00:00'):strtotime($productInfo['startTime']);
    $endTime = empty($productInfo['endTime'])?strtotime('00:00:00')+86399:strtotime($productInfo['endTime']);
    $timeExpect = empty($productInfo['timeExpect'])?60:$productInfo['timeExpect']; //每期时间
    $totalTime = $endTime - $startTime == 0 ? 86400 :$endTime - $startTime; //总时间
    $totalExpect = intval($totalTime / $timeExpect); //当天最多期数
    $nowTime = time(); //当前时间
    $nowExpectNumber =intval(($nowTime-$startTime)/$timeExpect);//当前期数
    $timeInterval = empty($productInfo['timeInterval'])?0:$productInfo['timeInterval'];
    //判断当前是否在开奖时间内 不在的话返回上一天最后一期，超出的话返回当天最后一期，在的话返回当前
    if ($nowExpectNumber < 0) {
        //小于0 则未到开奖时间 返回前一天最后一期
        $expectLast=date("Ymd",$nowTime - 86400).str_pad($totalExpect,(strlen($totalExpect)),0,STR_PAD_LEFT);
        $expectCurr = date("Ymd",$nowTime).str_pad('0',(strlen($totalExpect)),0,STR_PAD_LEFT);
        $openTime = $startTime - $nowTime;
    }elseif($nowExpectNumber > $totalExpect) {
        //大于总开奖结果 则返回当天最后一期
        $expectLast=date("Ymd",$nowTime).str_pad($totalExpect,(strlen($totalExpect)),0,STR_PAD_LEFT);
        $expectCurr =date("Ymd",$nowTime + 86400).str_pad('0',(strlen($totalExpect)),0,STR_PAD_LEFT);
        $openTime = $startTime + 86400 - $nowTime;
    }else{
        $expectLast=date("Ymd",$nowTime).str_pad($nowExpectNumber,(strlen($totalExpect)),0,STR_PAD_LEFT);
        //判断是否当天最后一期
        if ($nowExpectNumber >= $totalExpect) {
            //当天最后一期
            $expectCurr =date("Ymd",$nowTime + 86400).str_pad('0',(strlen($totalExpect)),0,STR_PAD_LEFT);
            $openTime = $startTime + 86400 - $nowTime;
        }else{
            //还有
            $expectCurr =date("Ymd",$nowTime).str_pad($nowExpectNumber + 1,(strlen($totalExpect)),0,STR_PAD_LEFT);
            $openTime = ($startTime + (($nowExpectNumber + 1) * $timeExpect)) - $nowTime;
        }
    }
    return [
        'expectLast'  => $expectLast ,
        'expectCurr'  => $expectCurr,
        'timeOpen'      => $openTime,
        'timeDisabled' => $openTime - $timeInterval,
    ];//
}

    public static function getApiTime($productInfo)
    {
//        $productInfo = self::fetch(['name' => $name]);
//        if (empty($productInfo)) {
//            return error(-10,'不存在此产品');
//        }
        if (in_array($productInfo['name'],['pc28jnd28'])) {
            $current = Game::fetch(['name' => $productInfo['name'],'order'=>true]);
            $expect = $current['expect'];
            $currentExpect = $current['expect'] + 1;
            $opentime = ($current['timeOpen'] / 1000 + $productInfo['timeExpect']) - time() ;
        }else{

        }
        $return = [
            'expectLast'  => $expect ,
            'expectCurr'  => $currentExpect,
            'timeOpen'      => $opentime,
        ];
        return $return;
    }

    public static function getOpenCode($name,$expect)
    {
        $productInfo = self::fetch(['name' => $name]);
        if (empty($productInfo)) {
            return error(-10,'不存在此产品');
        }
        $gameInfo = Game::fetch(['name' => $name,'expect' => $expect]);
        $returnData = [
            'expect' => $expect,
            'openCode' => '',
            'timeOpen' => '',

        ];
        if (!empty($gameInfo)){
                $returnData['openCode'] = $gameInfo['openCode'];
                $returnData['timeOpen'] = $gameInfo['timeOpen'];
            $returnData['data'] = [];
            if (in_array($gameInfo['type'],['pc28'])) {
                foreach ($gameInfo['extra'][1] as $v) {

                    $returnData['data'][] = lang($v);
                }
                list($a,$b,$c) = explode(',',$gameInfo['openCode']);
                $returnData['openCode'] .= ',' . ($a + $b + $c);
            }elseif(in_array($gameInfo['type'],['kl10f','ssc','kl8','x5'])){
                foreach ($gameInfo['extra'][0] as $v) {
                    $returnData['data'][] = lang($v);
                }
            }elseif(in_array($gameInfo['type'],['k3'])){
                // $returnData['data'] = [
                //     $gameInfo['extra'][0] + $gameInfo['extra'][1] + $gameInfo['extra'][2],
                //     lang($gameInfo['extra'][3]),
                // ];
                foreach ($gameInfo['extra'] as $v) {
                    $returnData['data'][] = lang($v);
                }
                
            }elseif(in_array($gameInfo['type'],['pk10'])){
                foreach ($gameInfo['extra'][0] as $v) {
                    $returnData['data'][] = lang($v);
                }
            }elseif ($gameInfo['type'] == 'lhc') {
                $returnData['data'] = $gameInfo['extra'];
            }
        }
        return $returnData;
    }

    public static function verifyOpenCode($type,$openCode) {
        $flag = false;
        $opencodes = explode(',',$openCode);
//        var_dump($opencodes);
//        var_dump(count($opencodes));
        if ($type == 'k3') {
            if (count($opencodes) == 3) {
                $info = Shop::open($openCode);
                return $info;
            }
        }elseif($type == 'pk10') {
            if (count($opencodes) == 10) {
                return true;
            }
        }
//        var_dump($flag);
        return $flag;
    }


    public static function getLongs($name = 'k318',$expect = '123')
    {
        $count = 5;
        $filters = [];
        $filters['name'] = $name;
        $filters['order']['id'] = 'desc';
        $list = \app\common\model\product\Game::search($filters,1,15);
        $type = $list[0]['type'];
        Long::remove(['name' => $name]);
        //
//        $list = [
//            [
//                'openCode' => '2,3,5',
//            ],[
//                'openCode' => '1,4,3',
//            ],[
//                'openCode' => '1,4,3',
//            ],[
//                'openCode' => '1,2,3',
//            ],[
//                'openCode' => '1,4,3',
//            ],[
//                'openCode' => '1,4,3',
//            ],[
//                'openCode' => '1,4,3',
//            ],[
//                'openCode' => '1,4,3',
//            ]
//        ];
        $handler = [];
        //格式化数组 重新排列开奖结果
        foreach ($list as $k=>$v) {
            $openCode = explode(',',$v['openCode']);
            foreach ($openCode as $k2 => $code) {
                $handler[$k2][] = $code;
            }
        }
        //取开奖结果每个开头第一个数值 作为对比关键
        $size = self::getRule($type); //大小   5等于 大 0 等于小
        $flag = [];
        foreach ($handler as $k=>$h) {
            $num = $h[0];
            $flag[$k]['size'] = $num >= $size ? '大':'小';
            $flag[$k]['quantity'] = $num %2 === 0 ? '双':'单';
        }
        //对比结果
        $result = [];
        foreach ($handler as $k=>$h) {
            $result[$k]['size'] = 0;
            $result[$k]['sizeFlag'] = $flag[$k]['size'];
            foreach ($h as $code) {
                $codeSize = $code >= $size ? '大':'小';
                if ($codeSize == $flag[$k]['size']) {
                    $result[$k]['size'] ++;
                }else{
                    if ($result[$k]['size'] < $count) {
                        $result[$k]['size'] =0;
                    }
                    break;
                }
            }
        }
        foreach ($handler as $k=>$h) {
            $result[$k]['quantity'] = 0;
            $result[$k]['quantityFlag'] = $flag[$k]['quantity'];
            foreach ($h as $code) {
                $codeSize = $code %2 === 0 ? '双':'单';
                if ($codeSize == $flag[$k]['quantity']) {
                    $result[$k]['quantity'] ++;
                }else{
                    if ($result[$k]['quantity'] < $count) {
                        $result[$k]['quantity'] =0;
                    }
                    break;
                }
            }
        }
        //插入数据库
        $newRow = [
            'type' => $type,
            'name' => $filters['name'],
            'expect' => $expect,
        ];
        foreach ($result as $k=>$res) {
            if (!empty($res['size'])) {
                $newRow['field'] = $res['sizeFlag'];
                $newRow['position'] = $k+1;
                $newRow['number'] = $res['size'];
                Long::add($newRow);
            }
            if (!empty($res['quantity'])) {
                $newRow['field'] = $res['quantityFlag'];
                $newRow['position'] = $k+1;
                $newRow['number'] = $res['quantity'];
                Long::add($newRow);
            }
        }
        return true;
    }

    public static function getRule($type)
    {
        $types = [
            'k3' => 4,
            'ssc' => 6,
            'pk10' => 6,
            'lhc' => 25
        ];
        return $types[$type];
    }
}